var that
const db = wx.cloud.database();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    IUSe:0,
    content: '',
    images: [],
    user: {},
    isLike:0,
    count:0,
    srcVideo:'',
    label:3,
    currentInput:''
  },
  /**
    * 生命周期函数--监听页面加载
    */
  onLoad: function (options) {
    that = this
    that.data.srcvideo=''
    //that.jugdeUserLogin();
   
  },
  getInput:function(e){
    that.setData({
      currentInput: e.detail.value
    })
  },
/**
 * 
 * 清空页面 
 */
clear:function(){
  console.log("qingk")
  that.data.textContent=''
  that.data.images= [],
  that.data.user= {},
  that.data.isLike=0,
  that.data.count=0,
  that.data.srcVideo='',
  that.data.label=3,
  that.setData({
    textContent:'',
    images: [],
    user: {},
    isLike:0,
    count:0,
    srcVideo:'',
    label:3,
  })
  console.log(that.data.currentInput)
},




  /**
   * 获取填写的内容
   */
  getTextAreaContent: function(event) {
    that.data.content = event.detail.value;
  },
/**
 * 
 * 标签选择
 */
radioChange:function(e){
  console.log(e.detail.value)
  that.data.label = e.detail.value
},
 /**
   * 选择图片
   */
  chooseImage: function(event) {
    that.setData.srcVideo=""
    that.setData({
      srcVideo:""
    })
    wx.chooseImage({
      count: 6,
      success: function(res) {
        // 设置图片
        that.setData({
          images: res.tempFilePaths,
        })
        that.data.images = []
        console.log(res.tempFilePaths)
        for (var i in res.tempFilePaths) {
          // 将图片上传至云存储空间
          wx.cloud.uploadFile({
            // 指定要上传的文件的小程序临时文件路径
            cloudPath: that.timetostr(new Date()),
            filePath: res.tempFilePaths[i],
            // 成功回调
            success: res => {
              that.data.images.push(res.fileID)
            },
          })
        }
      },
    })
  },
  /**
   * 图片路径格式化
   */
  timetostr(time){
    var randnum = Math.floor(Math.random() * (9999 - 1000)) + 1000;
    var str = randnum +"_"+ time.getMilliseconds() + ".png";
    return str;
  },
 
  //选择视频
  chooseVedio: function() {
    var that = this
    that.data.images=[]
    that.setData({
      images:[]
    })

    wx.chooseVideo({
      success: function(res) {
        console.log(res.tempFilePath)
        that.setData({
          srcVideo: res.tempFilePath,
        })
        //将视频上传置云存储空间
        wx.cloud.uploadFile({
          // 指定要上传的文件的小程序临时文件路径
          cloudPath: that.timetostr1(new Date()),
          filePath: res.tempFilePath,
          // 成功回调
          success: res => {
            that.data.srcVideo  = res.fileID
            that.setData({
              srcVideo : res.fileID
            })
            console.log(that.data.srcVideo)
          },
        })
      },
    })
  }, 
 /**
   * 视频路径格式化
   */
  timetostr1(time){
    var randnum = Math.floor(Math.random() * (9999 - 1000)) + 1000;
    var str = randnum +"_"+ time.getMilliseconds() + ".mp4";
    return str;
  },

  /**
   * 发布
   */
  formSubmit: function(e) {
    console.log('图片：', that.data.images)
    that.data.content = e.detail.value['input-content'];
    if(Object.keys(that.data.user).length===0){
      that.jugdeUserLogin();
    }
    else{
      if (that.data.images.length > 0){
        that.saveDataToServer();
      }else if(that.data.content.trim() != ''){
        that.saveDataToServer();
        console.log("进行内容保存")
      } else if(that.data.srcVideo.trim()!= ''){
        that.saveDataToServer();
      }else{
        wx.showToast({
          icon: 'none',
          title: '写点东西吧',
        })
      }
    }
  },
  /**
   * 保存到发布集合中
   */
  saveDataToServer: function(event) {
    console.log("updata添加数据")
    const db = wx.cloud.database()
    db.collection('topic').add({
      // data 字段表示需新增的 JSON 数据
      data: {
        content: that.data.content,
        date: new Date(),
        images: that.data.images,
        user: that.data.user,
        isLike:0,
        srcVideo:that.data.srcVideo,
        count:0,
        label:that.data.label,
         collect:0,
      },
      success: function(res) {
        // 清空数据
        that.data.content = "";
        that.data.images = [];
        that.data.srcvideo = "",
        that.setData({
          textContent: '',
          images: [],
          srcVideo:'',
          count:0,
          isLike:0,
          label:3,
        })
        that.showTipAndSwitchTab();
      },
    })
  },
  /**
   * 添加成功添加提示，切换页面
   */
  showTipAndSwitchTab: function(event) {
    wx.showToast({
      title: '新增记录成功',
    })
    wx.switchTab({
      url: '../index/index',
    })
  },
  /**
   * 删除图片
   */
  removeImg: function(event) {
    var position = event.currentTarget.dataset.index;
    that.data.images.splice(position, 1);
    // 渲染图片
    that.setData({
      images: that.data.images,
    })
  },
  // 预览图片
  previewImg: function(e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    wx.previewImage({
      //当前显示图片
      current: that.data.images[index],
      //所有图片
      urls: that.data.images
    })
  },
  /**
   * 判断用户是否登录
   */
  jugdeUserLogin: function(e) {
    // 查看是否授权
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res){
              that.data.user = res.userInfo;
              that.setData({
                user:that.data.user,
              })
            }
          })
        }
      }
      
    })
  },
 
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
  }
})